package com.loan.controller;

import com.loan.dto.Result;
import com.loan.entity.CreditCard;
import com.loan.repository.CreditCardRepository;
import com.loan.service.CreditCardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

/**
 * Created by huxudong on 17/7/10.
 */
@Controller
@RequestMapping("admin/card")
public class CardController {

    @Autowired
    private CreditCardRepository cardRepository;

    @Autowired
    private CreditCardService creditCardService;

    /**
     * 列表
     * @return
     */
    @RequestMapping(value = "list",method = RequestMethod.GET)
    public String list(Model model) {
        List<CreditCard> list = creditCardService.findByFlag(0);
        model.addAttribute("list", list);
        return "card/list";
    }

    /**
     * 新增or编辑
     * @return
     */
    @RequestMapping(value = "add",method = RequestMethod.GET)
    public String add(Model model,Long id) {
        if(id != null){
            CreditCard card = cardRepository.getOne(id);
            model.addAttribute("card", card);
        }

        return "card/add";
    }

    /**
     * 保存
     * @return
     */
    @RequestMapping(value = "save",method = RequestMethod.POST)
    @ResponseBody
    public Result save(CreditCard card) {
        Result result = new Result(200,"添加成功");
        if(card.getId() == null){
            card.setaTime(new Date());

        }else{
            CreditCard dbcard = cardRepository.getOne(card.getId());
            card.setaTime(dbcard.getaTime());
        }
        if(!card.getLogo().startsWith("http://")){
            card.setLogo("http://123.56.70.231:9090"+card.getLogo());
        }
        card.setcTime(new Date());
        cardRepository.save(card);
        return result;
    }

    /**
     * 删除
     * @return
     */
    @RequestMapping(value = "delete",method = RequestMethod.POST)
    @ResponseBody
    public Result delete(Long id) {
        Result result = new Result(200,"添加成功");
        cardRepository.delete(id);
        return result;
    }

}
